__author__ = 'buxiangjie'
"""
@time: 2024/2/9 22:35
"""

import os
import sys

# 把当前目录的父目录加到sys.path中
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
from datetime import datetime

import allure
import pytest
from selenium import webdriver
from log.ulog import logger_

from common.base import Option


def pytest_addoption(parser):
	parser.addoption("--env", default="zhidemai", help="运行环境")
	parser.addoption("--platform", default="linux", help="运行系统类型")
	parser.addoption("--browser", default="chrome", help="浏览器名称")


def pytest_configure(config):
	global env, platform, browser

	env = config.getoption("--env")
	platform = config.getoption("--platform")
	browser = config.getoption("--browser")


def pytest_collectstart(collector):
	collector._nodeid = f"{collector._nodeid}_{platform}_{browser}"


def pytest_itemcollected(item):
	item._nodeid = f"{item._nodeid}_{platform}_{browser}"


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
	"""
	当测试失败的时候，自动截图，展示到html报告中
	:param
	"""
	outcome = yield
	report = outcome.get_result()
	if report.when == "setup":
		if "TestIndex" in item.nodeid:
			allure.dynamic.feature(f"值得买官网测试_{platform}_{browser}")
	if report.when == 'call' or report.when == "setup":
		xfail = hasattr(report, 'wasxfail')
		if (report.skipped and xfail) or (report.failed and not xfail):
			_capture_screenshot()
			pass


def _capture_screenshot():
	"""截图保存为base64"""
	now_time = datetime.now().strftime("%Y%m%d%H%M%S")
	if not os.path.exists("./screenshot"):
		os.makedirs("screenshot")
	screen_path = os.path.join("screenshot", f"{now_time}.png")
	driver.save_screenshot(screen_path)
	allure.attach.file(screen_path, f"异常截图...{now_time}", allure.attachment_type.PNG)


@pytest.fixture(scope='session')
@allure.step("打开浏览器")
def drivers(request):
	global driver
	plat = Option(platform, browser)
	try:
		logger_.info("开始打开浏览器")
		logger_.info(plat.OPTION.to_capabilities())
		driver = webdriver.Remote(
			# 设定Node节点的URL地址，后续将通过访问这个地址连接到Node计算机
			command_executor=plat.PLATFORM,  # 要和节点机显示的ip地址一样
			options=plat.OPTION
		)
		logger_.info("打开浏览器成功")
		driver.maximize_window()
	except Exception as e:
		raise e

	@allure.step("关闭浏览器")
	def tear_down():
		driver.quit()

	# if os.path.exists("./screenshot"):
	# 	shutil.rmtree("./screenshot")
	request.addfinalizer(tear_down)
	return driver
